package com.mhc.haval.security.filter;

import com.mhc.haval.security.util.HtmlUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 继承此类，重写未登录或令牌过期导致认证失败时的处理方法
 *
 * @author Churry
 * @create 2017-09-19 20:16
 **/
@Component
public class CustomExceptionTranslationFilter extends ExceptionTranslationFilter {

//    @Bean
//    public AuthenticationEntryPoint authenticationEntryPoint(){
//         return new LoginUrlAuthenticationEntryPoint("/login");
//    }

    public CustomExceptionTranslationFilter() {
        super(new LoginUrlAuthenticationEntryPoint("/login"), new HttpSessionRequestCache());
    }

    /**
     * 重写未登录或令牌过期导致认证失败时的处理方法
     *
     * @param request
     * @param response
     * @param chain
     * @param reason
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException {
        Map<String, Object> responseMap = new HashMap<>(64);
        responseMap.put("data", null);
        responseMap.put("success", false);
        responseMap.put("code", HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
        responseMap.put("message", reason.getMessage());
        response.setStatus(HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
        HtmlUtil.writerJson(response, responseMap);
    }
}
